package com.diy.sigmund.diycommon.test.controller.other;

import com.alibaba.ttl.threadpool.TtlExecutors;
import com.diy.sigmund.diycommon.entity.ResultMsg;
import com.diy.sigmund.diycommon.spring.ContextHolder;
import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.DynamicThreadPoolManager;
import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.DynamicThreadPoolProperties;
import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.MonitorThreadFactory;
import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.ResizableCapacityLinkedBlockingQueue;
import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.ThreadPoolMonitor;
import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.ThreadPoolProperties;
import com.diy.sigmund.diycommon.util.json.JacksonUtil;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 动态修改线程池参数
 *
 * @author ylm-sigmund
 * @since 2023/1/29 22:33
 */
@RestController
@RequestMapping("/common")
public class DynamicThreadPoolPropertiesController {

    @Autowired
    private ContextRefresher contextRefresher;
    @Autowired
    private DynamicThreadPoolProperties dynamicThreadPoolProperties;
    @Autowired
    private DynamicThreadPoolManager dynamicThreadPoolManager;
    private static final Logger log = LoggerFactory.getLogger(DynamicThreadPoolPropertiesController.class);


    @PostMapping("/threadPool/update")
    public ResultMsg update() {
        ThreadPoolProperties threadPoolProperties = dynamicThreadPoolProperties.getExecutors().get(0);
        threadPoolProperties.setCorePoolSize(20);
        threadPoolProperties.setMaximumPoolSize(50);
        threadPoolProperties.setQueueCapacity(200);
        threadPoolProperties.setRejectedExecutionType("CallerRunsPolicy");

        ThreadPoolProperties threadPoolProperties1 = dynamicThreadPoolProperties.getExecutors().get(1);
        threadPoolProperties1.setCorePoolSize(21);
        threadPoolProperties1.setMaximumPoolSize(51);
        threadPoolProperties1.setQueueCapacity(201);
        threadPoolProperties1.setRejectedExecutionType("DiscardPolicy");

        Set<String> refresh = contextRefresher.refresh();
        return ResultMsg.success(refresh);
    }

    /**
     * 线程池,内存,cpu 数据监控
     *
     * @return ResultMsg
     */
    @GetMapping("/threadPool/properties")
    public ResultMsg queryThreadPoolProperties() {
        return ResultMsg.success(dynamicThreadPoolManager.getDynamicThreadPoolMetricMap());
    }

    private static final AtomicInteger number = new AtomicInteger(1);

    @PostMapping("/threadPool/call")
    public ResultMsg call() throws ExecutionException, InterruptedException {
        ThreadPoolMonitor threadPoolMonitor = dynamicThreadPoolManager.getThreadPoolExecutorMap().get("testDynamicThreadPool-1");

        log.info("主线程-当前线程的上下文信息customUser={}", JacksonUtil.toJson(ContextHolder.getInstance().getCustomUser()));
        CompletableFuture<String> future = CompletableFuture
                .supplyAsync(() -> {
                    log.info("hello 开始");
                    log.info("异步线程-当前线程的上下文信息customUser={}", JacksonUtil.toJson(ContextHolder.getInstance().getCustomUser()));
                    try {
                        // TimeUnit.MILLISECONDS.sleep(new Random().nextInt(4000));
                        TimeUnit.MILLISECONDS.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("hello 结束");
                    return "siting";
                }, TtlExecutors.getTtlExecutorService(threadPoolMonitor));
        String s = future.get();

        ThreadPoolMonitor threadPoolMonitor2 = dynamicThreadPoolManager.getThreadPoolExecutorMap().get("testDynamicThreadPool-2");

        Future<String> submit = threadPoolMonitor2.submit(() -> {
            log.info("threadPoolMonitor2 开始");
            log.info("异步线程-当前线程的上下文信息customUser={}", JacksonUtil.toJson(ContextHolder.getInstance().getCustomUser()));
            if (number.getAndIncrement() % 2 == 0) {
                return "threadPoolMonitor2 偶数";
            }
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("threadPoolMonitor2 结束");
            return "threadPoolMonitor2";
        });
        String s1 = submit.get();

        // Future<Void> submit1 = threadPoolMonitor2.submit(() -> {
        // threadPoolMonitor2.execute(() -> {
        TtlExecutors.getTtlExecutorService(threadPoolMonitor2).execute(() -> {
            log.info("threadPoolMonitor2 开始");
            log.info("异步线程-当前线程的上下文信息customUser={}", JacksonUtil.toJson(ContextHolder.getInstance().getCustomUser()));
            if (number.getAndIncrement() % 2 == 0) {
                log.info("threadPoolMonitor2 结束");
            }
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("threadPoolMonitor2 结束");
        });
        // Object o = submit1.get();

        // Future<?> submit2 = threadPoolMonitor2.submit(() -> {
        //     log.info("threadPoolMonitor2 开始");
        //     log.info("异步线程-当前线程的上下文信息customUser={}", JacksonUtil.toJson(ContextHolder.getInstance().getCustomUser()));
        //     if (number.getAndIncrement() % 2 == 0) {
        //         log.info("threadPoolMonitor2 结束");
        //     }
        //     try {
        //         TimeUnit.MILLISECONDS.sleep(300);
        //     } catch (InterruptedException e) {
        //         e.printStackTrace();
        //     }
        //     log.info("threadPoolMonitor2 结束");
        // },"success");
        // Object o1 = submit2.get();

        // return ResultMsg.success(s + " | " + s1);
        return ResultMsg.success();
    }

}

